//
//  UIView+Frame.m
//  传智微博
//
//  Created by apple on 15-3-5.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "UIView+Extension.h"
#import <objc/runtime.h>
//#import <Masonry/Masonry.h>
#import "UIView+Base.h"


const char * kTextInfo;
const char * kButtonClick;
const char * kIndexPath;
const char * klayoutBlock;
static char * vModel = "vModel";
static char * KRadius = "KRadius";
const char * kCellConfigDic;
const char * kViewConfigDic;


@interface UIColor (HcdCustom)

@property (nonatomic, readonly) CGColorSpaceModel colorSpaceModel;
@property (nonatomic, readonly) BOOL canProvideRGBComponents;
@property (nonatomic, readonly) CGFloat red; // Only valid if canProvideRGBComponents is YES
@property (nonatomic, readonly) CGFloat green; // Only valid if canProvideRGBComponents is YES
@property (nonatomic, readonly) CGFloat blue; // Only valid if canProvideRGBComponents is YES
@property (nonatomic, readonly) CGFloat white; // Only valid if colorSpaceModel == kCGColorSpaceModelMonochrome
@property (nonatomic, readonly) CGFloat alpha;
@property (nonatomic, readonly) UInt32 rgbHex;

+(UIColor *)colorWithHexString:(NSString *)color;

@end


@implementation UIView (Line)

//- (void)setHasTopLine:(BOOL)hasTopLine
//{
//    if (hasTopLine) {
//        UIView *l = [UIView new];
////        l.backgroundColor = [UIColor colorWithHexString:@"0xb6b6b6"];
//        l.backgroundColor = [UIColor colorWithHexString:@"#dbdbdb"];
//        l.tag = 1001;
//        [self addSubview:l];
//
//        [l mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.top.right.equalTo(l.superview);
//            make.height.mas_equalTo(1/[UIScreen mainScreen].scale);
//        }];
//    } else {
//        [[self viewWithTag:1001] removeFromSuperview];
//    }
//}

- (BOOL)hasTopLine
{
    return [self viewWithTag:1001] != nil;
}

//- (void)setHasBottomLine:(BOOL)hasBottomLine
//{
//    if (hasBottomLine) {
//        UIView *l = [UIView new]; //0xb6b6b6
//        l.backgroundColor = [UIColor colorWithHexString:@"#dbdbdb"];
//        l.tag = 1002;
//        [self addSubview:l];
//
//        [l mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.bottom.right.equalTo(l.superview);
//            make.height.mas_equalTo(1/[UIScreen mainScreen].scale);
//        }];
//
//
//    } else {
//        [[self viewWithTag:1002] removeFromSuperview];
//    }
//
//}

//-(void)setHasBottomSmallLine:(BOOL)hasBottomSmallLine
//{
//    if (hasBottomSmallLine) {
//        UIView *l = [UIView new];
////        l.backgroundColor = [UIColor colorWithHexString:@"0xb6b6b6"];
//        l.backgroundColor = [UIColor colorWithHexString:@"#dbdbdb"];
//        l.tag = 1002;
//        [self addSubview:l];
//        
//        [l mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.bottom.equalTo(l.superview);
//            make.left.equalTo(l.superview).offset(kFitW(15));
//            make.right.equalTo(l.superview).offset(kFitW(-15));
//            make.height.mas_equalTo(1/[UIScreen mainScreen].scale);
//        }];
//        
//        
//    } else {
//        [[self viewWithTag:1002] removeFromSuperview];
//    }
//}
//
//- (BOOL)hasBottomLine
//{
//    return [self viewWithTag:1002] != nil;
//}
//
//- (void)setHasLeftLine:(BOOL)hasLeftLine{
//    
//    UIView *l = [UIView new];
////    l.backgroundColor = [UIColor colorWithHexString:@"0xb6b6b6"];
//    l.backgroundColor = [UIColor colorWithHexString:@"#dbdbdb"];
//    l.tag = 1003;
//    [self addSubview:l];
//    
//    [l mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.bottom.top.equalTo(l.superview);
//        make.width.mas_equalTo(1/[UIScreen mainScreen].scale);
//    }];
//    [self bringSubviewToFront:l];
//}
//- (BOOL)hasLeftLine{
//    return [self viewWithTag:1003] != nil;
//}
//- (void)setHasRightLine:(BOOL)hasRightLine{
//    
//    UIView *l = [UIView new];
////    l.backgroundColor = [UIColor colorWithHexString:@"0xb6b6b6"];
//    l.backgroundColor = [UIColor colorWithHexString:@"#dbdbdb"];
//    l.tag = 1004;
//    [self addSubview:l];
//    
//    [l mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.bottom.top.equalTo(l.superview);
//        make.width.mas_equalTo(1/[UIScreen mainScreen].scale);
//    }];
//    [self bringSubviewToFront:l];
//}
//- (BOOL)hasRightLine{
//    
//    return [self viewWithTag:1004] != nil;
//    
//}
@end


@implementation UIView (Radius)
-(BOOL)isRadius
{
    return  [objc_getAssociatedObject(self,KRadius) intValue];
}
-(void)setIsRadius:(BOOL)isRadius
{
    objc_setAssociatedObject(self, KRadius,@(isRadius), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)setRadiusType:(UIRectCorner)type Radius:(CGFloat)radius
{
    if (self.isRadius==YES) {
        return ;
    }
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:type  cornerRadii:CGSizeMake(radius,0)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
    maskLayer.frame = self.bounds;
    self.isRadius=YES;
}
@end


@implementation UIView (OFView)

- (CGFloat)cornerRadius
{
    return self.layer.cornerRadius;
}

- (void)setCornerRadius:(CGFloat)cornerRadius
{
    self.layer.cornerRadius = cornerRadius;
}

- (CGFloat)borderWidth
{
    return self.layer.borderWidth;
}

- (void)setBorderWidth:(CGFloat)borderWidth
{
    if (borderWidth==0) {
        borderWidth =  1/[UIScreen mainScreen].scale;
    }
    self.layer.borderWidth = borderWidth;
}

- (CGSize)shadowOffset
{
    return self.layer.shadowOffset;
}

- (void)setShadowOffset:(CGSize)shadowOffset
{
    self.layer.shadowOffset = shadowOffset;
}

- (CGFloat)shadowOpacity
{
    return self.layer.shadowOpacity;
}

- (void)setShadowOpacity:(CGFloat )shadowOpacity
{
    self.layer.shadowOpacity = shadowOpacity;
}

- (UIColor *)shadowColor
{
    return (__bridge UIColor *)self.layer.shadowColor;
}

- (void)setShadowColor:(UIColor *)shadowColor
{
    self.layer.shadowColor = shadowColor.CGColor;
}

- (UIColor *)borderColor
{
    return (__bridge UIColor *)self.layer.borderColor;
}

- (void)setBorderColor:(UIColor *)borderColor
{
    self.layer.borderColor = borderColor.CGColor;
}

- (BOOL)masksToBounds
{
    return self.layer.masksToBounds;
}

- (void)setMasksToBounds:(BOOL)masksToBounds
{
    self.layer.masksToBounds = YES;
    
    
}

- (NSString *)bgColor
{
    return nil;
}

- (void)setBgColor:(NSString *)bgColor
{
    //self.backgroundColor = [UIColor colorWithHexString:bgColor];
    self.layer.backgroundColor = [UIColor colorWithHexString:bgColor].CGColor;
}

- (NSString *)bgImage
{
    return nil;
}

- (void)setBgImage:(NSString *)bgImage
{
    self.layer.contents = (__bridge id)[UIImage imageNamed:bgImage].CGImage;
    self.layer.contentsGravity = @"resizeAspectFill";
    self.layer.masksToBounds = YES;
//    UIImage *image = [IMAGE(@"background-img") scaleToSize:CGSizeMake(kScreenW, kScreenH)];
//    self.view.backgroundColor = [UIColor colorWithPatternImage:image];

}

- (UIImage *)backgroundImage
{
    return nil;
}

- (void)setBackgroundImage:(UIImage *)backgroundImage
{
    self.layer.contents=(__bridge id)backgroundImage.CGImage;
    self.layer.contentsGravity = @"resizeAspectFill";
}


-(void)viewCutRoundedOfRectCorner:(UIRectCorner)rectCorner cornerRadii:(CGFloat)cornerRadii
{
    /*
     类型共有以下几种:
     
     * UIRectCornerTopLeft
     
     * UIRectCornerTopRight
     
     * UIRectCornerBottomLeft
     
     * UIRectCornerBottomRight
     
     * UIRectCornerAllCorners
     
     */
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:rectCorner cornerRadii:CGSizeMake(cornerRadii, cornerRadii)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    
    maskLayer.frame = self.bounds;
    
    maskLayer.path = maskPath.CGPath;
    
    
    self.layer.mask = maskLayer;
}

@end


@implementation UIView (ACT)

-(void)setModel:(MABaseModel *)model
{
    objc_setAssociatedObject(self, vModel, model, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(MABaseModel *)model{
    return objc_getAssociatedObject(self, vModel);
}
-(void)setButtonBlcok:(void (^)(id, id, NSIndexPath *, id))buttonBlcok
{
 
    objc_setAssociatedObject(self, &kButtonClick,buttonBlcok, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void (^)(id, id, NSIndexPath *, id))buttonBlcok
{
    return  objc_getAssociatedObject(self, &kButtonClick);
}


-(void (^)(NSString *, id, id, NSIndexPath *, id))textBlcok
{
    return  objc_getAssociatedObject(self, &kTextInfo);
}


-(void)setTextBlcok:(void (^)(NSString *, id, id, NSIndexPath *, id))textBlcok
{

    objc_setAssociatedObject(self, &kTextInfo, textBlcok, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


-(void (^)(UIView *, CGPoint, CGSize, CGPoint))layoutBlock
{
    return  objc_getAssociatedObject(self, &klayoutBlock);
}
-(void)setLayoutBlock:(void (^)(UIView *, CGPoint, CGSize, CGPoint))layoutBlock
{
     objc_setAssociatedObject(self, &klayoutBlock, layoutBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


-(void)setIndexPath:(NSIndexPath *)indexPath
{
    objc_setAssociatedObject(self, &kIndexPath, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSIndexPath *)indexPath
{
    return  objc_getAssociatedObject(self, &kIndexPath);
}


-(NSMutableDictionary *)cellConfigDic
{
    return objc_getAssociatedObject(self,kCellConfigDic);
}


-(void)setCellConfigDic:(NSMutableDictionary *)cellConfigDic
{
    objc_setAssociatedObject(self, kCellConfigDic, cellConfigDic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


-(NSMutableDictionary *)viewConfigDic
{
    return objc_getAssociatedObject(self,kViewConfigDic);
}
-(void)setViewConfigDic:(NSMutableDictionary *)viewConfigDic
{
    objc_setAssociatedObject(self, kViewConfigDic, viewConfigDic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}


-(void)onChangeEditorEndForSub:(id)Sub
{
    if ([Sub isKindOfClass:[UITextField class]]) {
        UITextField *textF = Sub;
        
        if (self.textBlcok) {
            self.textBlcok(textF.text,self,Sub,self.indexPath,self.model);
        }
        
    }
    else if ([Sub isKindOfClass:[UITextView class]])
    {
        UITextView *textV = Sub;
        
        if (self.textBlcok) {
            self.textBlcok(textV.text,self,Sub,self.indexPath,self.model);
        }
    }
    else
    {
        
    }
    
    
}

-(void)onClickButtonForSub:(id)Sub
{
    if ([Sub isKindOfClass:[UIButton class]]) {
        UIButton *button = Sub;
        
        if (self.buttonBlcok) {
            self.buttonBlcok(self,button,self.indexPath,self.model);
        }
        
    }
    else if ([Sub isKindOfClass:[UIControl class]])
    {
        UIControl *control = Sub;
        
        if (self.buttonBlcok) {
            self.buttonBlcok(self,control,self.indexPath,self.model);
        }
    }
    else if([Sub isKindOfClass:[UISwitch class]])
    {
        UISwitch *Switch = Sub;
        if (self.buttonBlcok) {
            self.buttonBlcok(self,Switch,self.indexPath,self.model);
        }
    }
    else
    {
        
    }
}

-(void)onMainSetSubViewFrame:(void (^)(UIView *, CGPoint, CGSize, CGPoint))layoutBlock
{
    if (layoutBlock !=self.layoutBlock) {
        self.layoutBlock = layoutBlock;
    }
    
}
- (CGFloat)bottomFromSuperView{
    return self.superview.height - self.y - self.height;
}

- (void)addTarget:(id)target
           action:(SEL)action;
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:target
                                                                         action:action];
    self.userInteractionEnabled = YES;
    [self addGestureRecognizer:tap];
}

/**
 *  @brief  找到当前view所在的viewcontroler
 */
- (UIViewController *)viewController
{
    UIResponder *responder = self.nextResponder;
    do {
        if ([responder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)responder;
        }
        responder = responder.nextResponder;
    } while (responder);
    return nil;
}


- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}



- (BOOL)isShowingOnKeyWindow
{
    // 主窗口
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    // 以主窗口左上角为坐标原点, 计算self的矩形框
    CGRect newFrame = [keyWindow convertRect:self.frame fromView:self.superview];
    CGRect winBounds = keyWindow.bounds;
    
    // 主窗口的bounds 和 self的矩形框 是否有重叠
    BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);
    
    return !self.isHidden && self.alpha > 0.01 && self.window == keyWindow && intersects;
}
//-(void)viewWithRadius:(CGSize)radius{
//    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:radius];
//    CAShapeLayer *masklayer = [CAShapeLayer new];
//    masklayer.frame = self.bounds;
//    masklayer.path = maskPath.CGPath;
//    self.layer.mask = masklayer;

//    view.layer.cornerRadius = 5;//或者写view.layer.masksToBounds = YES;
//    view.clipsToBounds = YES;


//}


-(void)addV:(id)view{
    if (!view) return;
    if ([view isEqual:self]) return;
    [self addSubview:view];
}
-(void)addInSView:(id)supView{
    if (!supView) return;
    if ([supView isEqual:self]) return;
    [supView addSubview:self];
}


-(UIViewController *)currentViewController{
    UIViewController *vc;
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[objc_getClass("UIViewController") class]] ) {
            vc=(UIViewController*)nextResponder;
            
            return vc;
        }
    }
    return vc;
}


@end




@implementation UIColor (HcdCustom)

- (CGColorSpaceModel)colorSpaceModel {
    return CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor));
}

- (BOOL)canProvideRGBComponents {
    switch (self.colorSpaceModel) {
        case kCGColorSpaceModelRGB:
        case kCGColorSpaceModelMonochrome:
            return YES;
        default:
            return NO;
    }
}

- (CGFloat)red {
    NSAssert(self.canProvideRGBComponents, @"Must be an RGB color to use -red");
    const CGFloat *c = CGColorGetComponents(self.CGColor);
    return c[0];
}

- (CGFloat)green {
    NSAssert(self.canProvideRGBComponents, @"Must be an RGB color to use -green");
    const CGFloat *c = CGColorGetComponents(self.CGColor);
    if (self.colorSpaceModel == kCGColorSpaceModelMonochrome) return c[0];
    return c[1];
}

- (CGFloat)blue {
    NSAssert(self.canProvideRGBComponents, @"Must be an RGB color to use -blue");
    const CGFloat *c = CGColorGetComponents(self.CGColor);
    if (self.colorSpaceModel == kCGColorSpaceModelMonochrome) return c[0];
    return c[2];
}

- (CGFloat)white {
    NSAssert(self.colorSpaceModel == kCGColorSpaceModelMonochrome, @"Must be a Monochrome color to use -white");
    const CGFloat *c = CGColorGetComponents(self.CGColor);
    return c[0];
}

- (CGFloat)alpha {
    return CGColorGetAlpha(self.CGColor);
}

- (UInt32)rgbHex {
    NSAssert(self.canProvideRGBComponents, @"Must be a RGB color to use rgbHex");
    
    CGFloat r,g,b,a;
    if (![self red:&r green:&g blue:&b alpha:&a]) return 0;
    
    r = MIN(MAX(self.red, 0.0f), 1.0f);
    g = MIN(MAX(self.green, 0.0f), 1.0f);
    b = MIN(MAX(self.blue, 0.0f), 1.0f);
    
    return (((int)roundf(r * 255)) << 16)
    | (((int)roundf(g * 255)) << 8)
    | (((int)roundf(b * 255)));
}

- (BOOL)red:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha {
    const CGFloat *components = CGColorGetComponents(self.CGColor);
    
    CGFloat r,g,b,a;
    
    switch (self.colorSpaceModel) {
        case kCGColorSpaceModelMonochrome:
            r = g = b = components[0];
            a = components[1];
            break;
        case kCGColorSpaceModelRGB:
            r = components[0];
            g = components[1];
            b = components[2];
            a = components[3];
            break;
        default:	// We don't know how to handle this model
            return NO;
    }
    
    if (red) *red = r;
    if (green) *green = g;
    if (blue) *blue = b;
    if (alpha) *alpha = a;
    
    return YES;
}


+ (UIColor *) colorWithHexString: (NSString *)color
{
    return [self colorWithHexString:color alpha:1.f];
}


+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha
{
    //删除字符串中的空格
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6)
    {
        return [UIColor clearColor];
    }
    // strip 0X if it appears
    //如果是0x开头的，那么截取字符串，字符串从索引为2的位置开始，一直到末尾
    if ([cString hasPrefix:@"0X"])
    {
        cString = [cString substringFromIndex:2];
    }
    //如果是#开头的，那么截取字符串，字符串从索引为1的位置开始，一直到末尾
    if ([cString hasPrefix:@"#"])
    {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6)
    {
        return [UIColor clearColor];
    }
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:alpha];
}

@end
